//
//  Product_add_two_wifi_vc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/9.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Product_add_two_wifi_vc.h"
#import "Product_add_three_adding_vc.h"

#import "UIButton+SSEdgeInsets.h"
#import "MMAlertView.h"

#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <SystemConfiguration/CaptiveNetwork.h>

#import <CoreLocation/CoreLocation.h>
#import <NetworkExtension/NetworkExtension.h>

#import "LQFoldButtonCell.h"
#import "LQFoldButtonItem.h"

#import "Product_add_two_ble_vc.h"


@interface Product_add_two_wifi_vc ()<CLLocationManagerDelegate, UITableViewDelegate,UITableViewDataSource>
{
    CGSize __foldContentSize;
    BOOL __isFolded;
    CGRect __originRect;
    
    
}

@property (weak, nonatomic) IBOutlet UIButton *bg_btn;
@property (weak, nonatomic) IBOutlet UIImageView *tip_iv;
@property (weak, nonatomic) IBOutlet UITextField *pwd_tf;
@property (weak, nonatomic) IBOutlet UILabel *wifi_name_lb;
@property (nonatomic, copy) NSString *apBssid;


@property (strong, nonatomic) CLLocationManager *locationManager;
@property (weak, nonatomic) IBOutlet UITableView *foldTable;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *foldTable_height;
@property (nonatomic, strong)NSMutableArray *dataSource;
@property (nonatomic, assign)NSInteger selectedIndex;
@property (nonatomic, assign)CGFloat contentHeight;
@property (nonatomic, assign)CGFloat itemHeight;
@end

@implementation Product_add_two_wifi_vc
- (IBAction)bg_btn_click:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    sender.selected = !sender.selected;
    if (__isFolded) {
        [self close];
    } else {
        [self open];
    }
    
    sender.userInteractionEnabled = YES;
}
- (IBAction)next_action:(UIButton *)sender {
    if (self.wifi_name_lb.text.length ==0) {
        [MBProgressHUD showInfoMessage:@"请确认WiFi名称"];
        return;
    }
    if (self.pwd_tf.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您输入的密码为空，请再次确认" message:nil   preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.pwd_tf becomeFirstResponder];
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           [self push];
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self push];
    }
   
}

- (void)push{
    Product_add_three_adding_vc *vc= [[Product_add_three_adding_vc alloc]init];
       vc.hidesBottomBarWhenPushed = YES;
       vc.wifi_name = self.wifi_name_lb.text;
       vc.pwd = self.pwd_tf.text;
        vc.apBssid = self.apBssid;
    vc.aDevice =self.aDevice;

       [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)pwd_tf_see_action:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.pwd_tf.secureTextEntry = !self.pwd_tf.secureTextEntry;
}
- (NSString *)getWifiName{
    
    NSString *wifiName = @"未找到当前连接的Wi-Fi";
    
    CFArrayRef myArray = CNCopySupportedInterfaces();
    
    if (myArray != nil) {
        
        CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        
        if (myDict != nil) {
            
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            
            wifiName = [dict valueForKey:@"SSID"];
            self.apBssid = [dict valueForKey:@"BSSID"];
            CFRelease(myArray);
        }else{
            CFRelease(myArray);
        }
    }
    
    return wifiName;
}
/*
- (void)scanWifiInfos{// https://juejin.im/post/5a3214cd51882506fd589047
    NSLog(@"1.Start");
    
    NSMutableDictionary* options = [[NSMutableDictionary alloc] init];
    [options setObject:@"com.gzzyy.ainkjj" forKey: kNEHotspotHelperOptionDisplayName];
    dispatch_queue_t queue = dispatch_queue_create("com.gzzyy.ainkjj", NULL);
    
    NSLog(@"2.Try");
    BOOL returnType = [NEHotspotHelper registerWithOptions: options queue: queue handler: ^(NEHotspotHelperCommand * cmd) {
        
        NSLog(@"4.Finish");
        NEHotspotNetwork* network;
        if (cmd.commandType == kNEHotspotHelperCommandTypeEvaluate || cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) {
            // 遍历 WiFi 列表，打印基本信息
            for (network in cmd.networkList) {
                NSString* wifiInfoString = [[NSString alloc] initWithFormat: @"---------------------------\nSSID: %@\nMac地址: %@\n信号强度: %f\nCommandType:%ld\n---------------------------\n\n", network.SSID, network.BSSID, network.signalStrength, (long)cmd.commandType];
                NSLog(@"%@", wifiInfoString);
                
                // 检测到指定 WiFi 可设定密码直接连接
                if ([network.SSID isEqualToString: @"测试 WiFi"]) {
                    [network setConfidence: kNEHotspotHelperConfidenceHigh];
                    [network setPassword: @"123456789"];
                    NEHotspotHelperResponse *response = [cmd createResponse: kNEHotspotHelperResultSuccess];
                    NSLog(@"Response CMD: %@", response);
                    [response setNetworkList: @[network]];
                    [response setNetwork: network];
                    [response deliver];
                }
            }
        }
    }];
    
    // 注册成功 returnType 会返回一个 Yes 值，否则 No
    NSLog(@"3.Result: %@", returnType == YES ? @"Yes" : @"No");
}
 */

- (void)ble_page{
    Product_add_two_ble_vc *vc= [[Product_add_two_ble_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.aDevice = self.aDevice;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)dealloc{
    DLog();
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"蓝牙配网" style:UIBarButtonItemStylePlain target:self action:@selector(ble_page)];
    
    DLog(@"%@", [self getWifiName]);
    NSString *name = [self getWifiName];
    if (name.length > 0) {
        self.wifi_name_lb.text = name;
    }
    if(@available(iOS 13.0, *)){
        [self getUserLocation];
    }
    
    
    
   
    
    /*  [self scanWifiInfos];
     获取当前连接的Wi-Fi,显示其名称
     获取附近的Wi-Fi，备用
     
     https://blog.csdn.net/u010462316/article/details/98479184
     https://blog.csdn.net/xuanweihong_ios/article/details/98947025
     
     
     
     
     
     ————————————————
     版权声明：本文为CSDN博主「C_philadd」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。
     原文链接：https://blog.csdn.net/C_philadd/java/article/details/85161415
     
     
     - (BOOL)determineWhetherTheAPPOpensTheLocation{
     if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] ==kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
     return YES;
     } else {
     return NO;
     }
     }
     ————————————————
     版权声明：本文为CSDN博主「陈世流年」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。
     原文链接：https://blog.csdn.net/WangQingLei0307/article/details/102959000
     
     
     更详细的：
     https://blog.csdn.net/baidu_40537062/article/details/103034145
     */
    
    [self.bg_btn setEdgeInsetsWithType:SSEdgeInsetsTypeImage marginType:SSMarginTypeRight margin:0];
    
    _foldTable.delegate = self;
    _foldTable.dataSource = self;
    _foldTable.backgroundColor = [UIColor whiteColor];
    [_foldTable.layer setBorderColor:UIColor.lightGrayColor.CGColor];
    _foldTable.layer.borderWidth = 0.6;
    _contentHeight = 200.0;
    _itemHeight = 50.0;
    
    _selectedIndex = -1;
    NSArray *arr = @[@"手动输入Wi-Fi名称"];
    
    NSMutableArray *datas = [NSMutableArray arrayWithCapacity:arr.count];
    for (NSString *title in arr) {
        LQFoldButtonItem *item = [[LQFoldButtonItem alloc]init];
        item.title = title;
        [datas addObject:item];
    }
    
    self.dataSource = datas;
    [self.foldTable reloadData];
    
}
- (void)initSubviews{
    [super initSubviews];
    self.title = @"Wi-Fi配网";

}
#pragma mark - 定位授权代理方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusAuthorizedAlways) {
        //再重新获取ssid
        NSString *name = [self getWifiName];
        if (name.length > 0) {
            self.wifi_name_lb.text = name;
        }
    }else{
        [MBProgressHUD showErrorMessage:@"未开启定位，无法获取当前连接的WiFi名称"];
    }
}

- (void)getUserLocation{
    if (!self.locationManager) {
        self.locationManager = [[CLLocationManager alloc] init];
    }
    //如果用户第一次拒绝了，触发代理重新选择，要用户打开位置权限
    [self.locationManager requestAlwaysAuthorization];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1.0f;
    [self.locationManager startUpdatingLocation];
    
}

#pragma mark - UITableView 代理及数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LQFoldButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LQFoldButtonCell class])];
    if (cell == nil) {
        cell = [[LQFoldButtonCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([LQFoldButtonCell class])];
        cell.backgroundColor = tableView.backgroundColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.textAttribute = @{NSFontAttributeName: [UIFont systemFontOfSize:18], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
        
    }
    
    cell.item = [self.dataSource objectAtIndex:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.itemHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.selectedIndex = indexPath.row;
    LQFoldButtonItem * obj = [self.dataSource objectAtIndex:indexPath.row];
    __weak __typeof(self) weakSelf = self;
    if ([obj.title isEqualToString:@"手动输入Wi-Fi名称"]) {
        MMAlertView *alertView = [[MMAlertView alloc] initWithInputTitle:@"手动输入" detail:@"Wi-Fi名称" placeholder:@"请注意大小写" handler:^(NSString *text) {
            NSLog(@"input:%@",text);
            if (text.length > 0) {
                weakSelf.wifi_name_lb.text = text;
            }
            [weakSelf close];
        }];
        alertView.attachedView = weakSelf.view;
        alertView.attachedView.mm_dimBackgroundBlurEnabled = YES;
        alertView.attachedView.mm_dimBackgroundBlurEffectStyle = UIBlurEffectStyleExtraLight;
        [alertView show];
    }else{
        weakSelf.wifi_name_lb.text = obj.title;
        [weakSelf close];
    }
}
- (void) close {
    //如果已经关闭了,直接返回
    if (__isFolded == NO) {
        return;
    }
    __isFolded = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.foldTable_height.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    
}

- (void) open {
    //如果已经展开了,直接返回
    if (__isFolded == YES) {
        return;
    }
    __isFolded = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.foldTable_height.constant = 50;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}


@end



